import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Button, Message } from '@teamix/ui';
import { navigate } from 'utils/router';
import exceed from 'utils/apimap';
import './index.scss';
import intl from '../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class DeletePathResourceDialog extends React.Component {
  static propTypes = {
    closeModal: PropTypes.func,
    trigger: PropTypes.element,
    // 操作对象类型 代码库-repo 代码组-group
    type: PropTypes.oneOf(['repo', 'group']),
    // 对象名称用户二次确认展示
    name: PropTypes.string,
  };

  static defaultProps = {
    closeModal: () => {},
    trigger: PropTypes.element,
    type: '',
    name: '',
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  handleOk = () => {
    if (this.state.submitting) {
      return;
    }
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        this.remove(formData, (type) => {
          if (type === 'isFail') {
            this.field.reset();
          }
          this.setState({ submitting: false });
          this.onClose();
        });
      }
    });
  };

  remove = (formData, cb) => {
    const { pathResource } = window.FORCE;
    const { type } = this.props;
    exceed
      .fetch({
        api: `${type === 'repo' ? 'project' : 'groups'}.remove.with_reason`,
        params: { id: Number(pathResource.id) },
        data: formData,
      })
      .then((result) => {
        if (result.result === true) {
          Message.success({
            title: intl.get({
              id: 'code-assets.components.deletePathResourceDialog.Deleted',
              defaultMessage: '删除成功',
            }),
          });

          navigate('/');
          // navigate(href, { state: { forceUpdate: true } });
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.components.deletePathResourceDialog.UnableToDelete',
              defaultMessage: '删除失败',
            }),
          });
        }
        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态但是弹窗不关闭
        cb && cb('isFail');
      });
  };

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  nameValidator = (rule, value, callback) => {
    const { name, type } = this.props;
    if (!value) {
      callback();
      return;
    }
    if (name !== value) {
      callback(
        type === 'repo'
          ? intl.get({
              id: 'code-assets.components.deletePathResourceDialog.TheCodeLibraryNameIs',
              defaultMessage: '代码库名称输入错误，请重新输入',
            })
          : intl.get({
              id: 'code-assets.components.deletePathResourceDialog.TheErrorMessageReturnedBecause',
              defaultMessage: '代码组名称输入错误，请重新输入',
            }),
      );
    } else {
      callback();
    }
  };

  reasonValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (/^[ ]+$/.test(value)) {
      callback('删除原因不能全是空格');
    }
    if (value.length > 50) {
      callback(
        intl.get({
          id: 'code-assets.components.deletePathResourceDialog.TheReasonForDeletionCannot',
          defaultMessage: '删除原因不得超过 50 个字符',
        }),
      );
    } else {
      callback();
    }
  };

  render() {
    const { init } = this.field;
    const { type, name } = this.props;
    const disabled =
      !this.field.getValue('name') ||
      !this.field.getValue('reason') ||
      this.field.getError('name') ||
      this.field.getError('reason');
    const mainName =
      type === 'repo'
        ? intl.get({
            id: 'code-assets.components.deletePathResourceDialog.CodeBase',
            defaultMessage: '代码库',
          })
        : intl.get({
            id: 'code-assets.components.deletePathResourceDialog.CodeGroup',
            defaultMessage: '代码组',
          });
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            className="delete-path-resource"
            title={
              type === 'repo'
                ? intl.get({
                    id: 'code-assets.components.deletePathResourceDialog.DeleteACodeLibrary',
                    defaultMessage: '删除代码库',
                  })
                : intl.get({
                    id: 'code-assets.components.deletePathResourceDialog.DeleteACodeGroup',
                    defaultMessage: '删除代码组',
                  })
            }
            visible
            style={{ width: '440px' }}
            onClose={this.onClose}
            footer={
              <Button
                warning
                type="primary"
                style={{ width: '100%' }}
                onClick={this.handleOk}
                loading={!!this.state.submitting}
                disabled={!!disabled}
              >
                {intl.get({
                  id: 'code-assets.components.deletePathResourceDialog.ConfirmDeletion',
                  defaultMessage: '确认删除',
                })}
              </Button>
            }
          >
            <div style={{ marginBottom: '10px' }}>
              <Message
                title={intl.get(
                  {
                    id: 'code-assets.components.deletePathResourceDialog.MainnameWillBeMovedTo',
                    defaultMessage:
                      '{mainName}将移入回收站，数据最长保留15天，此期间支持手动恢复数据，超期数据将彻底删除，彻底删除后不可恢复',
                  },
                  { mainName },
                )}
                key="warning"
                type="warning"
                shape="inline"
              />
            </div>
            <Form {...formItemLayout} field={this.field} labelAlign="top">
              <FormItem
                label={
                  type === 'repo'
                    ? intl.get(
                        {
                          id: 'code-assets.components.deletePathResourceDialog.EnterTheCodeLibraryName',
                          defaultMessage: '请输入代码库名称 {name} 以确认删除',
                        },
                        { name },
                      )
                    : intl.get(
                        {
                          id: 'code-assets.components.deletePathResourceDialog.EnterTheCodeGroupName',
                          defaultMessage: '请输入代码组名称 {name} 以确认删除',
                        },
                        { name },
                      )
                }
                required
                className="delete-path-resource-name"
              >
                <Input
                  autoFocus
                  placeholder={
                    type === 'repo'
                      ? intl.get({
                          id: 'code-assets.components.deletePathResourceDialog.EnterACodeLibraryName',
                          defaultMessage: '请输入代码库名称',
                        })
                      : intl.get({
                          id: 'code-assets.components.deletePathResourceDialog.EnterACodeGroupName',
                          defaultMessage: '请输入代码组名称',
                        })
                  }
                  {...init('name', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.nameValidator,
                      },
                    ],
                  })}

                  // id="delete-name"
                />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.components.deletePathResourceDialog.ReasonForDeletion',
                  defaultMessage: '删除原因',
                })}
                required
              >
                <Input
                  placeholder={intl.get({
                    id: 'code-assets.components.deletePathResourceDialog.EnterTheReasonForDeletion',
                    defaultMessage: '请输入删除原因，不超过 50 个字符',
                  })}
                  maxLength={50}
                  hasLimitHint
                  {...init('reason', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.reasonValidator,
                      },
                    ],
                  })}
                />
              </FormItem>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}
      </React.Fragment>
    );
  }
}
